package org.offsync.nio

import java.net.ServerSocket
import java.net.SocketAddress
import java.nio.channels.SelectionKey
import java.nio.channels.ServerSocketChannel
import org.offsync.rich._
import org.offsync.util.DisposableBase

case class NioServerSocketChannel(
    protected override val channel: ServerSocketChannel
    ) extends NioSelectableChannel(channel) with DisposableBase {
  def accept(selector: NioOpSelector)(f: NioSocketChannel => Unit): Unit = {
    channel.register(
        selector.selector,
        SelectionKey.OP_READ,
        {
          val socketChannel = channel.accept()
          socketChannel.configureBlocking(false)
          f(NioSocketChannel(socketChannel))
        })
  }
  
  def socket: ServerSocket = channel.socket()
  
  def bind(
      socketAddress: SocketAddress) = socket.bind(socketAddress)
  
  protected override def onDispose(): Unit = {
    try channel.close() catch { case e => } finally super.onDispose()
  }
}

object NioServerSocketChannel {
  def open(): NioServerSocketChannel = {
    val channel = ServerSocketChannel.open()
    channel.configureBlocking(false)
    return NioServerSocketChannel(channel)
  }
}
